package com.keeley.ctrl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.ext.route.ControllerBind;
import com.keeley.content.Content;
import com.keeley.model.LoginLog;
import com.keeley.model.User;
import com.keeley.pageModel.LoginInfo;
@SuppressWarnings({ "unchecked", "rawtypes" })
@ClearInterceptor
@ControllerBind(controllerKey="/",viewPath="/common")
public class HomeController  extends AdminBaseController {
	
	
	public HomeController() {
		super(null);
	}
    public void index() {
		User user = getCurrentUser();
		if(user==null)
			render("/common/login.html");
		else
			render("/common/index.html");
	}
	public void login(){
		String username = getPara("username");
		String password = getPara("password");
		User user=User.dao.checkUser(username, password);
		if(user==null){
			this.rendJson_(false, "用户名密码不正确");
			return;
		}
		
		String ip = this.getRequest().getHeader("X-Real-IP");
		Date time=new Date();
		if(ip==null){
			ip=this.getRequest().getRemoteAddr();
		}
		LoginLog loginLog=new LoginLog();
		loginLog.set("user_id", user.getInt("id")).set("ip", ip).set("login_time", time).save();

		
		
		this.setCookie(Content.SESSION_LOGIN_LOG_ID,loginLog.getLong("id").toString(),60*12);//12小时
		setSessionAttr(Content.SESSION_LOGIN_USER, user);
		this.rendJson_(true, "登录成功");
	}
	@Before(SessionInViewInterceptor.class)
	public void north(){
	}
	
	public void logout(){
		String loginLogId=this.getCookie(Content.SESSION_LOGIN_LOG_ID);
		if(loginLogId!=null&&!"".equals(loginLogId)){
			LoginLog.dao.findById(loginLogId).set("logout_time", new Date()).update();
		}
		this.removeCookie(Content.SESSION_LOGIN_LOG_ID);
		this.removeSessionAttr(Content.SESSION_LOGIN_USER);
		this.redirect("/");
	}
}